from django.urls import reverse
import requests
import json
import base64
from django.shortcuts import render, redirect
from django.http import JsonResponse

from datetime import datetime

# Create your views here.

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    if request.method == 'POST':
        # 获取前端发送的数据
        account_info = json.loads(request.body)
        username = account_info.get('username')
         
        password = base64.b64decode(account_info.get('password')).decode('utf-8')
        url = "http://pax.biubiubiu.io/api/v1/auth/ldap"
        data = {
            "name": username,
            "password": password
        }
        print('111', data)
        response = requests.post(url, json=data)

        token = response.json()
        print(token)
        if token['success']:
            token = token['data']['token']
            return JsonResponse({
                'success': True,
                'token': token,
                'redirect_url': reverse('pax_index')  # 返回跳转地址
            })
        else:
            return JsonResponse({
                'success': False,
                'error_msg': token['message']
            })
    
def pax_index(request):
    return render(request, 'index.html')

def main(token, uids, server_name, attchments,mail_type):
    for attchment in attchments:
        attchment['ItemId'] = int(attchment['ItemId'])
    headers = {
        "Content-Type": "application/json",
        "authorization": f"Bearer {token}",
    }
    cookies = {
        "projectInfo": json.dumps({"sign":"sausage-intranet","env":"pro"})
    }
    url = "http://pax.biubiubiu.io/sausage-intranet/server/otv/send_mail/"
    if mail_type == "sausage":
        mail_type = 0
    else:
        mail_type = 1
    data = {
  "mail_system_type": mail_type,
  "uids": uids,
  "client_type": 0,
  "attachments": attchments,
  "all": False,
  "weight": None,
  "desc": "",
  "expire_time": 0,
  "init_player_time": 0,
  "msgs": {
    "lan_set": [
      {
        "lan_code": 0,
        "body": ""
      }
    ]
  },
  "server_name": server_name
}
    response = requests.post(url, headers=headers, cookies=cookies, json=data)
    print(response.json())
    if "detail" in response.json() and "认证失败" in response.json()['detail']:
        return { "status": 401}
    
    if "发送成功" in response.json()['msg']:
        return {
                'success': True
            }
    else:
        return {
                'success': False,
                'msg': response.json()['msg']
            }
def send_email(request):
    if request.method == 'POST':
        # 获取前端发送的数据
        data = json.loads(request.body)
        uids = data.get('uids')
        server_name = data.get('server_name')
        token = data.get('token','')
        attachments = data.get('attachments')
        mail_type = data.get('mail_type')
        print('这是附件::', attachments, type(attachments))
        print('这是token::', token, type(token))
        print('server_name::', server_name, type(server_name))
        print('mail_type::', mail_type, type(mail_type))
        
        result = main(token,uids,server_name,attachments,mail_type)
        if result.get('status'):
            return JsonResponse({
                    'success': False,
                    'message': result.get('detail', '未知错误')
                }, status=401)
        if result['success']:
            return JsonResponse({
                    'success': True
                })
        else:
            print('rrr', result)
            if '失败' in result['msg']:
                return JsonResponse({
                    'success': False,
                    'message': result.get('msg', '未知错误')
                })
            else:
                return JsonResponse({
                        'success': False,
                        'message': result.get('detail', '未知错误')
                    })
            
def item_view(request):
    token = request.META.get('HTTP_AUTHORIZATION')
    server = request.GET.get('server')
    print('sss', server)
    print('sss222', token)
    # mail_type = request.GET.get('mail_type')
    headers = {
    "authorization": f"Bearer {token}"}
    # "authorization": f"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTM4LCJuYW1lIjoieWFuZ3RpYW5sb25nIiwicm9sZU5hbWUiOiIiLCJpc19sZGFwIjp0cnVlLCJpYXQiOjE3NDg3NzUwMDUsImV4cCI6MTc0OTIwNzAwNX0.1Eb3_YPBuGeRbHbz8HU8MDubnq8dhc2P2HbAEXyVvdg"}
    cookies = {
        "projectInfo": "{%22sign%22:%22sausage-intranet%22%2C%22env%22:%22pro%22}"
    }
    url = "http://pax.biubiubiu.io/sausage-intranet/server/otv/send_mail_view/"
    params = {
        "server_name": server
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params, verify=False)

    a = {
        "golddash_items": [],
        "sausage_items": [],
    }
    if response.status_code == 200:
        for i in response.json()['data']['tarkov_items']:
            a['golddash_items'].append({"label":i['name'],"value":str(i['id'])})
        for i in response.json()['data']['items']:
            a['sausage_items'].append({"label":i['name'],"value":str(i['id'])})
        return JsonResponse({
                        'success': True,
                        'data': a
                    })
    else:
        return JsonResponse({
                        'success': False,
                        'data': a
                    })
    
def server_view(request):
    # 获取 Authorization 头
    token = request.META.get('HTTP_AUTHORIZATION')
    headers = {
    "authorization": f"Bearer {token}"}
    cookies = {
        "projectInfo": "{%22sign%22:%22sausage-intranet%22%2C%22env%22:%22pro%22}"
    }
    url = "http://pax.biubiubiu.io/sausage-intranet/server/siv/"
    result = []
    for i in range(2):
        params = {
            "vm_type": i
        }
        try:
            response = requests.get(url, headers=headers, cookies=cookies, params=params, verify=False)
            for i in response.json()['data']:
                result.append({
                    "label": i["server_name"],
                    "title": i["branch"],
                    "value": i["server_name"],
                })
        except Exception as e:
            print('报错了,', e)
            return JsonResponse({
                            'success': False,
                            'data': None,
                            'msg': "服务器列表获取失败."
                        })
    return JsonResponse({
                    'success': True,
                    'data': result,
                    'msg': "服务器列表获取成功."
                })
def iso_to_timestamp_milliseconds(iso_str):
    # 替换 'Z' 为 '+00:00'（因为 fromisoformat 不支持 'Z'）
    dt = datetime.fromisoformat(iso_str.replace('Z', '+00:00'))
    # 转换为秒级时间戳
    timestamp_seconds = dt.timestamp()
    # 转换为毫秒级（11 位）
    timestamp_milliseconds = int(timestamp_seconds * 1000)
    return timestamp_milliseconds

def god_skill(request):
    # 增加段位积分  update_score 
    # 跳过新手引导  beginner_tutorial_process 
    # 跳过新手引导（海外）  beginner_tutorial
    token = request.META.get('HTTP_AUTHORIZATION')
    username = request.POST.get('username')
    server_name = request.POST.get('server_name')
    uid = request.POST.get('uid')
    query_key = request.POST.get('query_key')
    score = request.POST.get('score')
    set_time = request.POST.get('set_time')
    infra_id = request.POST.get('infra_id')
    infra_level = request.POST.get('infra_level')
    # print('ss2', request.POST)
    # print("infra_id:", infra_id, type(infra_id))
    # print("infra_level:", infra_level, type(infra_level))
    # print(iso_to_timestamp_milliseconds(set_time))
    url = "http://pax.biubiubiu.io/sausage-intranet/server/test-tool/get_httpapi_request/"
    query_data = {
        "uid": uid
    }
    if query_key == "update_score":
        query_data['score'] = int(score)
    elif query_key == "european":
        query_data['percent'] = 100
        query_data['reason'] = "hello"
    elif query_key == "infrastructure":
        query_data['infra_id'] = int(infra_id)
        query_data['level'] = int(infra_level)
    data = {
        "username": "yangtianlong",
        "server_name": server_name,
        "data": {
            "data": json.dumps(query_data),
            "game_server_uri": f"/unittest/player/{query_key}",
            "match_server_key_replace": "",
            "match_server_uri": ""
        }
    }
    if query_key == "open_all_match_mode":
        data['data']['game_server_uri'] = "/unittest/custom_match_config/open_all_match_mode"
    elif query_key == "close_all_match_mode":
        data['data']['game_server_uri'] = "/unittest/custom_match_config/close_all_match_mode"
    elif query_key == "unlock_all_pve_difficulty":
        data['data']['game_server_uri'] = "/unittest/pve/unlock_all_pve_difficulty"
    elif query_key == "unlock_all_pve_handbook":
        data['data']['game_server_uri'] = "/unittest/pve/unlock_all_pve_handbook"
    elif query_key == "european":
        data['data']['game_server_uri'] = "/unittest/item/european"
    elif query_key == "infrastructure":
        data['data']['game_server_uri'] = "/unittest/gold_dash_infrastructure/set_infrastructure_level"
    elif query_key == "get_now_time":
        data['data'] = {
    "data": "{}",
    "chat_server_uri": "/unittest/time/get_now_time",
    "data_info_uri": "/unittest/helper/get_now_time",
    "data_node_uri": "/unittest/helper/get_now_time",
    "friend_uri": "/unittest/time/get_now_time",
    "game_server_uri": "/unittest/time/get_now_time",
    "lottery_uri": "/unittest/time/get_now_time",
    "match_server_key_replace": "",
    "match_server_uri": "/unittest/grpc_server/get_now_time",
    "method": "GET",
    "player_rankings_uri": "/unittest/helper/get_now_time",
    "pps_uri": "/unittest/test/get_now_time",
    "red_point_uri": "/unittest/time/get_now_time"
}
    elif query_key == "set_now_time":
        data['data'] = {
  "data": json.dumps({"now_time": int(iso_to_timestamp_milliseconds(set_time) / 1000)}),
  "chat_server_uri": "/unittest/time/set_now_time",
  "data_info_uri": "/unittest/helper/set_now_time",
  "data_node_uri": "unittest/helper/set_now_time",
  "friend_uri": "/unittest/time/set_now_time",
  "game_server_uri": "/unittest/time/set_now_time",
  "lottery_uri": "/unittest/time/set_now_time",
  "match_server_key_replace": "{\"now_time\":\"nowTime\"}",
  "match_server_uri": "/unittest/grpc_server/set_now_time",
  "method": "POST",
  "player_rankings_uri": "/unittest/helper/set_now_time",
  "pps_uri": "/unittest/test/set_now_time",
  "red_point_uri": "/unittest/time/set_now_time"
}
    headers = {
        "Content-Type": "application/json",
        "authorization": f"Bearer {token}",
        # "authorization": f"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTM4LCJuYW1lIjoieWFuZ3RpYW5sb25nIiwicm9sZU5hbWUiOiIiLCJpc19sZGFwIjp0cnVlLCJpYXQiOjE3NDg5MjkwMDcsImV4cCI6MTc0OTM2MTAwN30.aKEaXC18QMk__1_Z6KC_rdyoiGzn_ivKQmGvQ3oA7Is",
    }
    cookies = {
        "projectInfo": json.dumps({"sign":"sausage-intranet","env":"pro"})
    }
    print(data)
    res = requests.post(url=url, json=data, headers=headers, cookies=cookies)
    print(res.status_code)
    if res.status_code == 200:
        result = res.json()['data']
        print(result)
        if query_key == "get_now_time":
            for i in result:
                if i.startswith("data_info"):
                    server_time = result[i]['now']
                    return JsonResponse(
                                {
                                    "success": True,
                                    "data": server_time
                                }
                            )
        elif query_key == "set_now_time":

            return JsonResponse(
                        {
                            "success": True,
                        }
                    )
        for i in result:
            if query_key in ["european", "open_all_match_mode", "close_all_match_mode"]:
                if result[i]['succ']:
                    return JsonResponse(
                        {
                            "success": True
                        }
                    )
            else:
                if "success" in result[i]:
                    return JsonResponse(
                        {
                            "success": True
                        }
                    )
        return JsonResponse(
                    {
                        "success": False
                    }
                )
    else:
        return JsonResponse(
                    {
                        "success": False
                    }
                )